<template>
	<div ref="chartBox"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
	name: 'BasicEcharts',
	props: {
		isAxisChart: {
			type: Boolean,
			default: true
		},
		chartData: {
			type: Object,
			default: () => {
				return {
					legendData: [],
					xData: [],
					series: []
				}
			}
		}
	},
	data() {
		return {
			axisOption: {
				textStyle: {
					color: '#333'
				},
				legend: {
					data: []
				},
				grid: {
					left: 10,
					right: 10,
					bottom: 10,
					containLabel: true
				},
				tooltip: {
					trigger: 'axis'
				},
				xAxis: {
					type: 'category',
					data: [],
					axisLine: {
						lineStyle: {
							color: '#17b3a3'
						}
					},
					axisLabel: {
						interval: 0,
						color: '#333'
					}
				},
				yAxis: [
					{
						type: 'value',
						axisLine: {
							lineStyle: {
								color: '#17b3a3'
							}
						}
					}
				],
				series: []
			},
			noAxisOption: {
				tooltip: {
					trigger: 'item'
				},
				legend: {
					data: []
				},
				series: []
			},
			echartInst: null
		}
	},
	computed: {
		options() {
			return this.isAxisChart ? this.axisOption : this.noAxisOption;
		}
	},
	watch: {
		chartData: {
			handler() {
				this.initChart();
			},
			deep: true
		}
	},
	mounted() {
		window.addEventListener("resize", () => {
      this.echartInst.resize();
    });
	},
	methods: {
		initChart() {
			this.initChartData();
			if (!this.echartInst) {
				this.echartInst = echarts.init(this.$refs.chartBox);
			}
			this.echartInst.setOption(this.options);
		},
		initChartData() {
			if (this.isAxisChart) {
				this.axisOption.legend.data = this.chartData.legendData; 
				this.axisOption.xAxis.data = this.chartData.xData;
				this.axisOption.series = this.chartData.series;
			} else {
				this.noAxisOption.legend.data = this.chartData.legendData;
				this.noAxisOption.series = this.chartData.series;
			}
		}
	}
}
</script>
